package com.lanhai.longheng.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lanhai.longheng.interfaces.ICmdLog;
import com.lanhai.longheng.interfaces.ISendData;

@Service
public class DataSendTools implements ISendData {

	 private static final Logger agvlog = LogManager.getLogger("agvlog");	

	 private static final Logger devicelog = LogManager.getLogger("agvlog");	 
	
	 
	@Autowired
	ICmdLog cmdLog;
	
	 @Override
	public   void sendAgvData(int agvid,String ip,int port,String remark,byte[] data) {
		if(data.length<4) return;
		cmdLog.addAgvSendLog(agvid, remark, Tools.byte2HexStr(data));
		 
		//发送
		try {

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(baos);
			InetAddress is = InetAddress.getByName("10.23.101.200");
			DatagramSocket ds = new DatagramSocket(0, is);// 让java随机指定端口

			dos.write(data);
			byte[] buf = baos.toByteArray();
			DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress(ip, port));
			ds.send(dp);
			ds.close();
		} catch (Exception e1) {
			agvlog.error("agv指令发送失败", e1);
		} 
	}
	
	 
	 
	 
	 /**
	 *向机台发送
	 */
	@Override
	public  synchronized void sendDeviceData(String ip,int port,int line,String remark,byte[] data,String devicename) {
		if(data.length<2) return;
		cmdLog.addDeviceSendLog(ip, port,line, remark, Tools.byte2HexStr(data),devicename);
		 
		//发送
		 
		try {

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(baos);
		    InetAddress is = InetAddress.getByName("172.16.111.67");
			DatagramSocket   ds = new DatagramSocket(9701,is);//让java随机指定端口
			   
			dos.write(data);
			byte[] buf = baos.toByteArray();
			DatagramPacket dp = new DatagramPacket(buf, buf.length,
					new InetSocketAddress(ip, port));
			ds.send(dp);
			ds.close();
		} catch (Exception e1) {
			devicelog.error("对接机台指令发送失败", e1);
		}  
	}
}
